package diseaseandcureadministration.disease;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

import diseaseandcureadministration.AbstractLoader;
import diseaseandcureadministration.cure.Cure;
import diseaseandcureadministration.cure.CureCreator;
import diseaseandcureadministration.cure.ICureCreator;
import diseaseandcureadministration.registry.Registrable;
import diseaseandcureadministration.registry.Registry;
import diseaseandcureadministration.symptom.Symptom;
import diseaseandcureadministration.symptom.SymptomRegistry;

/**
 * DiseaseFlieLoader is a concrete AbstractLoader
 * 
 * @author Peter Tolstrup Aagesen, ptaa@itu.dk
 *
 */
public class DiseaseFileLoader extends AbstractLoader
{	
	//Instance variables
	private Registry _symptomRegistry;
	private ICureCreator _cureCreator;
	
	DiseaseFileLoader()
	{		
		//Construct super and set variables
		super();
		setFileName("data\\diseases.txt");	
		_symptomRegistry = SymptomRegistry.getRegistryInstance();		
		_cureCreator = new CureCreator();
	}

	@Override
	public ArrayList<Registrable> load() throws FileNotFoundException 
	{
		ArrayList<Registrable> diseases = new ArrayList<Registrable>();
		Disease disease;
		
		File diseasesFile = new File(getFileName());
		Scanner scanner = new Scanner(diseasesFile);
		
		try
		{
			//Traverse file
			while(scanner.hasNextLine())
			{
				String line = scanner.nextLine();
				
				//Get the name of the disease
				int positionOfFirstComma = line.indexOf(',');
				String name = line.substring(0, positionOfFirstComma);
				
				//Get the symptoms
				int positionOfSymptoms = line.indexOf("s:") +2;
				int endOfSymptoms = line.indexOf("c:");
				//Get the substring containing the symptoms
				String symptomsAsString = line.substring(positionOfSymptoms, endOfSymptoms);
				//Convert to array by "chopping" at every comma
				String[] symptomsAsStringArray = symptomsAsString.split(", ");
				ArrayList<Symptom> symptoms = new ArrayList<Symptom>();				
				for(int i = 0; i < symptomsAsStringArray.length; i++)
				{
					//Get symptom from SymptomRegistry
					Symptom symptom = (Symptom) _symptomRegistry.getElementByName(symptomsAsStringArray[i]);
					symptoms.add(symptom);
				}
				
				//Get cure
				int positionOfCure = line.indexOf("c:") + 2;
				String cureAsString = line.substring(positionOfCure);
				//Get cure from factory
				Cure cure = _cureCreator.getCure(cureAsString);
				
				//Create new disease element and add it
				disease = new Disease(name, symptoms, cure);
				diseases.add(disease);				
			} 		
		}
		//Ensure the Scanner is closed
		finally
		{
			scanner.close();
		}
		
		return diseases;
	}

}
